package com.mirror.llk;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Toast;

import com.mirror.llk.bean.domain.TTheme;
import com.mirror.llk.logic.ThemeLogic;
import com.mirror.llk.utils.Constant;
import com.mirror.llk.utils.TempConstant;
import com.mirror.llk.view.DiyView;
import com.mirror.utils.base.BaseActivity;
import com.mirror.utils.base.VerifyResult;
import com.mirror.utils.io.FileUtils;

public class DIYActivity extends BaseActivity {

	/** 日志标签 */
	private String TAG = "DIYActivity";

	private DiyView diyView;

	private ThemeLogic logic = new ThemeLogic();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		diyView = new DiyView(this);
		setContentView(diyView);
		this.init();
	}

	private void init() {

		initPhotoListener();

		diyView.btnClear.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				FileUtils.clearDir(Constant.LOCATION_HIGH_PHOTO, Constant.DIR_TEMP_FILE);
				for (ImageView imageView : diyView.ivList) {
					diyView.clearImage(imageView);
				}

			}
		});

		diyView.btnSave.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				VerifyResult<TTheme> result = null;
				try {
					result = diyView.verifySubmit();
					if (result.isPass()) {
						logic.saveLocaTheme(result.getBean());
						setResult(RESULT_OK);
						finish();
					} else {
						Toast.makeText(DIYActivity.this, result.getToast(), Toast.LENGTH_SHORT).show();
					}
				}
				catch (Exception e) {
					setResult(RESULT_CANCELED);
					finish();
				}
			}
		});
		diyView.skChoose.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
				diyView.initPhotoArea(progress);
				initPhotoListener();
			}
		});
	}

	private void initPhotoListener() {
		for (ImageView imageView : diyView.ivList) {
			imageView.setOnClickListener(listener);
			diyView.setImage(imageView);
		}
	}

	private OnClickListener listener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			TempConstant.getInstance().setImageId(v.getId());
			loadPhoto();
		}
	};

	/**
	 * 拍照
	 */
	private void loadPhoto() {
		final Context dialogContext = new ContextThemeWrapper(DIYActivity.this, android.R.style.Theme_Light);
		String[] choices;
		choices = new String[2];
		choices[0] = getString(R.string.action_photo_camera); // 拍照
		choices[1] = getString(R.string.action_photo_picture); // 从相册中选择
		final ListAdapter adapter = new ArrayAdapter<String>(dialogContext, android.R.layout.simple_list_item_1, choices);

		final AlertDialog.Builder builder = new AlertDialog.Builder(dialogContext);
		builder.setTitle(R.string.action_upload_photo);
		builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				switch (which) {
					case 0:
						String status = Environment.getExternalStorageState();
						if (status.equals(Environment.MEDIA_MOUNTED)) {// 判断是否有SD卡
							// 用户点击了从照相机获取
							String sdStatus = Environment.getExternalStorageState();
							if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
								Log.d(TAG, "SD card is not avaiable/writeable right now.");
								return;
							}
							// 调用android自带的照相机
							Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
							int imageId = TempConstant.getInstance().getImageId();
							intent.putExtra(MediaStore.EXTRA_OUTPUT, getInUri(String.valueOf(imageId)));
							startActivityForResult(intent, 1);
						} else {
							Toast.makeText(DIYActivity.this, "没有SD卡", Toast.LENGTH_LONG).show();
						}
						break;
					case 1:
						Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
						intent.addCategory(Intent.CATEGORY_OPENABLE);
						intent.setType("image/*");
						startActivityForResult(intent, 4);
						break;
				}
			}
		});
		builder.create().show();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
			case 1: // 完成照相后回调用此方法
				switch (resultCode) {
					case Activity.RESULT_OK:// 照相完成点击确定
						int imageId = TempConstant.getInstance().getImageId();
						startActivityForResult(createCropIntent(ACTION_CROP, getInUri(String.valueOf(imageId)), getOutUri(String.valueOf(imageId))),
						                       2);
						break;
					case Activity.RESULT_CANCELED:// 取消
						break;
				}
				break;
			case 2:
				switch (resultCode) {
					case Activity.RESULT_OK:
						if (isXiaoMi()) {
							int imageId = TempConstant.getInstance().getImageId();
							ImageView imageView = (ImageView) findViewById(imageId);
							diyView.setImage(imageView);
						} else {
							int imageId = TempConstant.getInstance().getImageId();
							String fileName = "IMG_" + imageId + ".png";
							String path = FileUtils.getFilePath() + Constant.LOCATION_HIGH_PHOTO + Constant.DIR_TEMP_FILE + fileName;
							Bitmap photo = data.getParcelableExtra("data");
							photo = FileUtils.convertToBitmap(photo, 100, 100);
							FileUtils.saveFile(photo, path);
							((ImageView) findViewById(imageId)).setImageBitmap(photo);
						}
						break;
					case Activity.RESULT_CANCELED:// 取消
						break;
				}
				break;
			case 4:
				switch (resultCode) {
					case Activity.RESULT_OK:
						Uri uri = data.getData();
						int imageId = TempConstant.getInstance().getImageId();
						startActivityForResult(createCropIntent(ACTION_CROP, uri, getOutUri(String.valueOf(imageId))), 2);
						break;
					case Activity.RESULT_CANCELED:// 取消
						break;
				}
				break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
}
